package xin.marcher.module.label.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import xin.marcher.module.label.domain.dto.*;
import xin.marcher.module.label.domain.request.CategoryLabelGroupRelastionRequest;
import xin.marcher.module.label.domain.request.QueryCategoryLabelGroupRelationDetailRequest;
import xin.marcher.module.label.repository.LabelRelationRepository;
import xin.marcher.module.label.repository.LabelRepository;
import xin.marcher.module.label.service.CategoryLabelGroupRelationService;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 *
 */
@Service
public class CategoryLabelGroupRelationServiceImpl implements CategoryLabelGroupRelationService {

    @Autowired
    private LabelRelationRepository labelRelationRepository;

    @Autowired
    private LabelRepository labelRepository;


    @Override
    public CategoryLabelGroupRelationResultDTO saveCategoryLabelGroupRelastion(CategoryLabelGroupRelastionRequest request) {
        return labelRelationRepository.saveCategoryLabelGroupRelation(request);
    }

    @Override
    public List<CategoryLabelGroupRelationDetailDTO> getCategoryLabelGroupRelationDetail(QueryCategoryLabelGroupRelationDetailRequest request) {
        // 查询出关联关系
        List<CategoryLabelGroupRelationDTO> labelGroupRelationDTOS = labelRelationRepository
                .listCategoryLabelGroupRelationByCategoryId(request.getCategoryId());
        if (CollectionUtil.isEmpty(labelGroupRelationDTOS)) {
            return Collections.emptyList();
        }

        // 查询出标签组
        List<Long> groupIds = labelGroupRelationDTOS.stream().map(CategoryLabelGroupRelationDTO::getLabelGroupId).collect(Collectors.toList());
        List<LabelGroupDTO> labelGroupDTOS = labelRepository.listLabelGroups(groupIds);

        // 查询出标签组内的标签
        List<LabelDTO> labelDTOS = labelRepository.listLabelByGroupIds(groupIds);
        if (CollectionUtil.isEmpty(labelDTOS)) {
            return Collections.emptyList();
        }

        // 封装结果
        Map<Long, List<LabelDTO>> groupIdLablesMap = labelDTOS.stream().collect(Collectors.groupingBy(LabelDTO::getGroupId));
        List<CategoryLabelGroupRelationDetailDTO> result = new ArrayList<>();
        for (LabelGroupDTO e : labelGroupDTOS) {
            CategoryLabelGroupRelationDetailDTO dto = new CategoryLabelGroupRelationDetailDTO();
            dto.setLabelGroupDTO(e);
            dto.setLabelDTOS(groupIdLablesMap.getOrDefault(e.getId(), Collections.emptyList()));
            result.add(dto);
        }
        return result;
    }
}
